<template>
  <div id="app">
    <el-config-provider :locale="locale" :size="size">
      <!-- 布局容器 -->
      <el-container v-if="showLayout" class="layout-container">
        <!-- 侧边栏 -->
        <el-aside :width="sidebarWidth" class="sidebar" v-show="!isMobile || showMobileSidebar">
          <div class="sidebar-header">
            <div class="logo" @click="$router.push('/')">
              <el-icon :size="28"><Reading /></el-icon>
              <h1 v-show="!isCollapsed">教案管理平台</h1>
            </div>
          </div>
          <el-menu
            :default-active="currentRoute"
            :collapse="isCollapsed"
            :collapse-transition="false"
            router
            class="sidebar-menu"
          >
            <el-menu-item index="/home">
              <el-icon><HomeFilled /></el-icon>
              <template #title>首页</template>
            </el-menu-item>
            <el-menu-item index="/lesson-plans">
              <el-icon><Document /></el-icon>
              <template #title>我的教案</template>
            </el-menu-item>
            <el-menu-item index="/public-lessons">
              <el-icon><Reading /></el-icon>
              <template #title>公开教案</template>
            </el-menu-item>
            <el-menu-item index="/lesson-plans/create">
              <el-icon><DocumentAdd /></el-icon>
              <template #title>创建教案</template>
            </el-menu-item>
            <el-sub-menu index="category" v-if="authStore.user?.role === 'admin'">
              <template #title>
                <el-icon><Management /></el-icon>
                <span>系统管理</span>
              </template>
              <el-menu-item index="/admin/categories">分类管理</el-menu-item>
              <el-menu-item index="/admin/users">用户管理</el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-aside>
        
        <!-- 主体内容 -->
        <el-container class="main-container" :style="{ marginLeft: sidebarWidth }">
          <!-- 顶部导航栏 -->
          <el-header class="header">
            <div class="header-left">
              <el-button
                v-if="!isMobile"
                :icon="isCollapsed ? Expand : Fold"
                @click="toggleSidebar"
                text
                class="collapse-btn"
              />
              <el-button
                v-else
                :icon="Menu"
                @click="toggleMobileSidebar"
                text
                class="mobile-menu-btn"
              />
              <!-- 面包屑导航 -->
              <el-breadcrumb separator="/" class="breadcrumb" v-if="!isMobile">
                <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item v-if="currentPageName">{{ currentPageName }}</el-breadcrumb-item>
              </el-breadcrumb>
            </div>
            
            <div class="header-right">
              <!-- 搜索框 -->
              <div class="header-search" v-if="!isMobile">
                <el-input
                  v-model="globalSearch"
                  placeholder="搜索教案..."
                  :prefix-icon="Search"
                  @keyup.enter="handleGlobalSearch"
                  clearable
                />
              </div>
              
              <!-- 通知图标 -->
              <el-popover
                placement="bottom-end"
                :width="380"
                trigger="click"
                @show="handleShowNotifications"
              >
                <template #reference>
                  <el-badge :value="notificationCount" :hidden="notificationCount === 0" class="notification-badge">
                    <el-button :icon="Bell" circle text />
                  </el-badge>
                </template>
                <div class="notification-popover">
                  <div class="notification-header">
                    <h4>通知</h4>
                    <el-button v-if="unreadNotifications.length > 0" link @click="markAllAsRead">
                      全部标记已读
                    </el-button>
                  </div>
                  <div v-if="loadingNotifications" class="notification-loading">
                    <el-icon class="is-loading"><Loading /></el-icon>
                    加载中...
                  </div>
                  <div v-else-if="notifications.length === 0" class="notification-empty">
                    <el-empty description="暂无通知" :image-size="80" />
                  </div>
                  <div v-else class="notification-list">
                    <div
                      v-for="notification in notifications"
                      :key="notification._id"
                      class="notification-item"
                      :class="{ unread: !notification.isRead }"
                      @click="handleNotificationClick(notification)"
                    >
                      <div class="notification-content">
                        <h5>{{ notification.title }}</h5>
                        <p>{{ notification.content }}</p>
                        <span class="notification-time">{{ formatNotificationTime(notification.createdAt) }}</span>
                      </div>
                      <div v-if="!notification.isRead" class="unread-dot"></div>
                    </div>
                  </div>
                  <div class="notification-footer">
                    <el-button link @click="router.push('/notifications')">查看全部通知</el-button>
                  </div>
                </div>
              </el-popover>
              
              <!-- 用户菜单 -->
              <el-dropdown v-if="authStore.isAuthenticated" @command="handleCommand" trigger="click">
                <div class="user-info">
                  <el-avatar :size="36" :src="userAvatarUrl" class="user-avatar">
                    {{ authStore.user?.name?.charAt(0) }}
                  </el-avatar>
                  <span class="username" v-if="!isMobile">{{ authStore.user?.name }}</span>
                  <el-icon><ArrowDown /></el-icon>
                </div>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="profile">
                      <el-icon><User /></el-icon>
                      个人资料
                    </el-dropdown-item>
                    <el-dropdown-item command="settings">
                      <el-icon><Setting /></el-icon>
                      设置
                    </el-dropdown-item>
                    <el-dropdown-item divided command="logout">
                      <el-icon><SwitchButton /></el-icon>
                      退出登录
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <div v-else class="auth-buttons">
                <el-button @click="$router.push('/login')">登录</el-button>
                <el-button type="primary" @click="$router.push('/register')">注册</el-button>
              </div>
            </div>
          </el-header>
          
          <!-- 主内容区域 -->
          <el-main class="main-content">
            <transition name="fade-slide" mode="out-in">
              <RouterView :key="route.fullPath" />
            </transition>
          </el-main>
          
          <!-- 底部信息 -->
          <el-footer class="footer" height="40px">
            <div class="footer-content">
              <span>© 2025 教案管理平台</span>
              <span class="footer-divider">|</span>
              <span>v1.0.0</span>
            </div>
          </el-footer>
        </el-container>
      </el-container>
      
      <!-- 全屏页面（登录、注册等） -->
      <RouterView v-else />
      
      <!-- 移动端遮罩层 -->
      <div v-if="isMobile && showMobileSidebar" class="mobile-mask" @click="showMobileSidebar = false"></div>
    </el-config-provider>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { RouterView, useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowDown,
  Expand,
  Fold,
  Menu,
  Search,
  Bell,
  User,
  Setting,
  SwitchButton,
  HomeFilled,
  Document,
  DocumentAdd,
  Management,
  Reading,
  Loading
} from '@element-plus/icons-vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { useAuthStore } from '@/stores/auth'
import { notificationApi } from '@/api/notification'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
const locale = zhCn

// 响应式状态
const isCollapsed = ref(false)
const showMobileSidebar = ref(false)
const globalSearch = ref('')
const notificationCount = ref(0)
const windowWidth = ref(window.innerWidth)
const notifications = ref<any[]>([])
const loadingNotifications = ref(false)
const unreadNotifications = computed(() => notifications.value.filter(n => !n.isRead))

// 响应式配置
const size = computed(() => isMobile.value ? 'default' : 'default')
const isMobile = computed(() => windowWidth.value < 768)
const sidebarWidth = computed(() => {
  if (isMobile.value) return '200px'
  return isCollapsed.value ? '64px' : '200px'
})

// 用户头像URL
const userAvatarUrl = computed(() => {
  // 使用 store 的 avatarTimestamp 来强制更新
  const timestamp = authStore.avatarTimestamp
  
  if (!authStore.user?.avatar) return ''
  
  // 如果已经是完整URL，直接返回
  if (authStore.user.avatar.startsWith('http')) {
    return `${authStore.user.avatar}?t=${timestamp}`
  }
  
  // 开发环境下使用代理，直接返回相对路径
  // 生产环境需要配置 VITE_API_BASE_URL
  return `${authStore.user.avatar}?t=${timestamp}`
})

// 当前路由
const currentRoute = computed(() => route.path)

// 当前页面名称
const currentPageName = computed(() => {
  const routeMap: Record<string, string> = {
    '/lesson-plans': '教案管理',
    '/lesson-plans/create': '创建教案',
    '/public-lessons': '公开教案',
    '/profile': '个人资料',
    '/admin/categories': '分类管理',
    '/admin/users': '用户管理'
  }
  
  if (route.path.startsWith('/lesson-plans/') && route.path.includes('/edit')) {
    return '编辑教案'
  }
  if (route.path.startsWith('/lesson-plans/') && !route.path.includes('/create')) {
    return '教案详情'
  }
  
  return routeMap[route.path] || ''
})

// 是否显示布局（登录页、注册页等不显示）
const showLayout = computed(() => {
  const noLayoutRoutes = ['/login', '/register', '/forgot-password']
  return !noLayoutRoutes.includes(route.path)
})

// 切换侧边栏
const toggleSidebar = () => {
  isCollapsed.value = !isCollapsed.value
  localStorage.setItem('sidebarCollapsed', String(isCollapsed.value))
}

// 切换移动端侧边栏
const toggleMobileSidebar = () => {
  showMobileSidebar.value = !showMobileSidebar.value
}

// 全局搜索
const handleGlobalSearch = () => {
  if (globalSearch.value.trim()) {
    router.push({
      path: '/lesson-plans',
      query: { q: globalSearch.value }
    })
    globalSearch.value = ''
  }
}

// 处理用户菜单命令
const handleCommand = async (command: string) => {
  switch (command) {
    case 'logout':
      try {
        await ElMessageBox.confirm('确定要退出登录吗？', '退出确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await authStore.logout()
        ElMessage.success('已退出登录')
        router.push('/login')
      } catch (error) {
        // 用户取消操作
      }
      break
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      ElMessage.info('设置功能开发中...')
      break
  }
}

// 监听窗口大小变化
const handleResize = () => {
  windowWidth.value = window.innerWidth
  if (!isMobile.value) {
    showMobileSidebar.value = false
  }
}

// 获取未读通知数量
const fetchUnreadCount = async () => {
  if (!authStore.isAuthenticated) return
  
  try {
    const { data } = await notificationApi.getUnreadCount()
    notificationCount.value = data.count
  } catch (error) {
    console.error('获取未读通知数量失败:', error)
  }
}

// 显示通知列表
const handleShowNotifications = async () => {
  loadingNotifications.value = true
  try {
    const { data } = await notificationApi.getNotifications({ limit: 10 })
    notifications.value = data.notifications
  } catch (error) {
    console.error('获取通知列表失败:', error)
    ElMessage.error('获取通知失败')
  } finally {
    loadingNotifications.value = false
  }
}

// 处理通知点击
const handleNotificationClick = async (notification: any) => {
  // 标记为已读
  if (!notification.isRead) {
    try {
      await notificationApi.markAsRead(notification._id)
      notification.isRead = true
      notificationCount.value = Math.max(0, notificationCount.value - 1)
    } catch (error) {
      console.error('标记已读失败:', error)
    }
  }
  
  // 跳转到相关页面
  if (notification.relatedModel === 'LessonPlan' && notification.relatedId) {
    router.push(`/lesson-plans/${notification.relatedId}`)
  }
}

// 标记所有为已读
const markAllAsRead = async () => {
  try {
    await notificationApi.markAllAsRead()
    notifications.value.forEach(n => n.isRead = true)
    notificationCount.value = 0
    ElMessage.success('已标记所有通知为已读')
  } catch (error) {
    console.error('标记全部已读失败:', error)
    ElMessage.error('操作失败')
  }
}

// 格式化通知时间
const formatNotificationTime = (time: string) => {
  const date = new Date(time)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(diff / 3600000)
  const days = Math.floor(diff / 86400000)
  
  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`
  
  return date.toLocaleDateString('zh-CN')
}

// 监听路由变化，移动端自动关闭侧边栏
watch(() => route.path, () => {
  if (isMobile.value) {
    showMobileSidebar.value = false
  }
})

// 初始化
onMounted(async () => {
  // 恢复侧边栏状态
  const savedCollapsed = localStorage.getItem('sidebarCollapsed')
  if (savedCollapsed !== null) {
    isCollapsed.value = savedCollapsed === 'true'
  }
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
  
  // 检查登录状态
  if (authStore.token && !authStore.user) {
    try {
      await authStore.fetchCurrentUser()
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  }
  
  // 获取未读通知数量
  fetchUnreadCount()
  
  // 定期刷新未读通知数量
  const notificationInterval = setInterval(fetchUnreadCount, 30000) // 每30秒刷新一次
  
  // 组件卸载时清理
  onUnmounted(() => {
    clearInterval(notificationInterval)
  })
})

// 清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  line-height: 1.5;
  background-color: #f0f2f5;
  color: #303133;
}

#app {
  min-height: 100vh;
}

.layout-container {
  min-height: 100vh;
}

/* 侧边栏样式 */
.sidebar {
  position: fixed;
  top: 0;
  left: 0;
  height: 100vh;
  background: white;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.06);
  transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  z-index: 1001;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.sidebar-header {
  height: 60px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  border-bottom: 1px solid #e4e7ed;
}

.logo {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.logo:hover {
  transform: scale(1.02);
}

.logo h1 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  white-space: nowrap;
  transition: opacity 0.3s;
}

.logo .el-icon {
  color: #409eff;
}

.sidebar-menu {
  flex: 1;
  border-right: none;
  overflow-y: auto;
  overflow-x: hidden;
}

.sidebar-menu:not(.el-menu--collapse) {
  width: 200px;
}

.sidebar-menu .el-menu-item,
.sidebar-menu .el-sub-menu__title {
  height: 48px;
  line-height: 48px;
}

.sidebar-menu .el-menu-item.is-active {
  background-color: #ecf5ff;
  color: #409eff;
  font-weight: 500;
}

/* 顶部导航栏 */
.header {
  background: white;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  height: 60px !important;
  padding: 0 24px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: sticky;
  top: 0;
  z-index: 999;
}

.header-left,
.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.collapse-btn,
.mobile-menu-btn {
  font-size: 18px;
}

.breadcrumb {
  margin-left: 16px;
}

.header-search {
  width: 240px;
}

.header-search .el-input {
  border-radius: 20px;
}

.notification-badge {
  margin-right: 8px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 4px 12px;
  border-radius: 20px;
  transition: all 0.3s;
}

.user-info:hover {
  background-color: #f5f7fa;
}

.user-avatar {
  border: 2px solid #e4e7ed;
}

.username {
  font-size: 14px;
  color: #606266;
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.auth-buttons {
  display: flex;
  gap: 12px;
}

/* 主容器 */
.main-container {
  transition: margin-left 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 主内容区域 */
.main-content {
  padding: 24px;
  background-color: #f0f2f5;
  flex: 1;
}

/* 底部信息 */
.footer {
  background: white;
  border-top: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: center;
}

.footer-content {
  display: flex;
  align-items: center;
  gap: 16px;
  font-size: 12px;
  color: #909399;
}

.footer-divider {
  color: #dcdfe6;
}

/* 动画效果 */
.fade-slide-enter-active,
.fade-slide-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.fade-slide-enter-from {
  opacity: 0;
  transform: translateX(30px);
}

.fade-slide-leave-to {
  opacity: 0;
  transform: translateX(-30px);
}

/* 移动端样式 */
@media (max-width: 768px) {
  .sidebar {
    transform: translateX(-100%);
  }
  
  .sidebar[style*="display: block"] {
    transform: translateX(0);
  }
  
  .main-container {
    margin-left: 0 !important;
  }
  
  .mobile-mask {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 1000;
  }
  
  .header {
    padding: 0 16px;
  }
  
  .main-content {
    padding: 16px;
  }
  
  .header-search,
  .breadcrumb {
    display: none;
  }
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* Element Plus 覆盖样式 */
.el-button--text {
  padding: 8px;
}

.el-dropdown-menu__item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.el-dropdown-menu__item .el-icon {
  font-size: 16px;
}

/* 通知弹窗样式 */
.notification-popover {
  padding: 0;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #e4e7ed;
}

.notification-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

.notification-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 40px;
  color: #909399;
}

.notification-empty {
  padding: 20px;
}

.notification-list {
  max-height: 400px;
  overflow-y: auto;
}

.notification-item {
  position: relative;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f2f5;
  cursor: pointer;
  transition: background-color 0.3s;
}

.notification-item:hover {
  background-color: #f5f7fa;
}

.notification-item.unread {
  background-color: #f0f9ff;
}

.notification-content h5 {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.notification-content p {
  margin: 0 0 4px 0;
  font-size: 13px;
  color: #606266;
  line-height: 1.4;
}

.notification-time {
  font-size: 12px;
  color: #909399;
}

.unread-dot {
  position: absolute;
  top: 50%;
  right: 16px;
  transform: translateY(-50%);
  width: 8px;
  height: 8px;
  background-color: #409eff;
  border-radius: 50%;
}

.notification-footer {
  padding: 12px 16px;
  text-align: center;
  border-top: 1px solid #e4e7ed;
}
</style>